package com.koubei.distribute.consistent.hash;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class HashFunction {

	static String hashName = "MD5"; // MD5 gives good enough accuracy in most circumstances. Change to SHA1 if it's needed
	static final MessageDigest digestFunction;
	static { // The digest method is reused between instances to provide higher entropy.
		MessageDigest tmp;
		try {
			tmp = java.security.MessageDigest.getInstance(hashName);
		} catch (NoSuchAlgorithmException e) {
			tmp = null;
		}
		digestFunction = tmp;
	}

	public static int hash(String data) {
		int h = 0;
		byte[] res;

		synchronized (digestFunction) {
			res = digestFunction.digest(data.getBytes());
		}

		for (int i = 0; i < 4; i++) {
			h <<= 8;
			h |= ((int) res[i]) & 0xFF;
		}
		return h;
	}

}
